﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Media;
using System.Diagnostics;

namespace Assergs.Windows
{
    /// <summary>
    /// Need 3 value
    /// 0: ListViewItem
    /// 1: Brush for AlternateHighlight
    /// 2: Percent transparent
    /// </summary>
    public class ListViewAlternateHighlightConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values == null)
                return null;
            Debug.Assert(values.Length >= 2);

            ListViewItem item = (ListViewItem)values[0];
            ListView listView =
                ItemsControl.ItemsControlFromItemContainer(item) as ListView;
            // Get the index of a ListViewItem
            int index = listView.ItemContainerGenerator.IndexFromContainer(item);

            if (index % 2 == 0)
            {
                return item.Background;
            }
            else
            {
                Brush tempBrush = (Brush)values[1];
                Type type = tempBrush.GetType();
                double percentA;
                if (double.TryParse((string)values[2], out percentA))
                {
                    if (type == typeof(LinearGradientBrush))
                    {
                        LinearGradientBrush linearGradientBrush = (LinearGradientBrush)tempBrush;
                        LinearGradientBrush linearGradientBrushReturn = new LinearGradientBrush() { StartPoint = linearGradientBrush.StartPoint, EndPoint = linearGradientBrush.EndPoint };
                        foreach (GradientStop gstop in linearGradientBrush.GradientStops)
                        {
                            byte bA = (byte)((percentA * gstop.Color.A / 100) % (byte.MaxValue + 1));
                            linearGradientBrushReturn.GradientStops.Add
                                (
                                new GradientStop(Color.FromArgb(bA, gstop.Color.R, gstop.Color.G, gstop.Color.B), gstop.Offset)
                                );
                        }
                        return linearGradientBrushReturn;
                    }
                }
                else
                    return values[1] as Brush;
            }
            return null;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
